import 'package:flutter/material.dart';
import '../models/user.dart';
import '../services/auth_service.dart';
import '../utils/storage_util.dart';

class UserProvider extends ChangeNotifier {
  final AuthService _authService = AuthService();

  bool _isLoading = false;
  bool get isLoading => _isLoading;
  bool _isAdmin = false;
  bool get isAdmin => _isAdmin;
  String _currentRole = '';
  String get currentRole => _currentRole;

  User? _user;
  User? get user => _user;

  List<String> _roles = [];
  List<String> get roles => _roles;

  List<String> _permissions = [];
  List<String> get permissions => _permissions;

  Future<bool> fetchUserInfo() async {
    _setLoading(true);
    try {
      final res = await _authService.getUserInfo();
      final userData = res['user'];
      final roleList = List<String>.from(res['roles'] ?? []);
      final permissionList = List<String>.from(res['permissions'] ?? []);

      if (userData == null) {
        throw '用户数据为空';
      }

      _user = User.fromJson(userData);
      _roles = roleList;
      _permissions = permissionList;
      _isAdmin = roleList.any((role) => ['admin', 'manager', 'fishingceo'].contains(role));

      // 保存用户信息到本地存储
      await _saveUserInfoToStorage(userData);

      notifyListeners();
      return true;
    } catch (e, stackTrace) {
      return false;
    } finally {
      _setLoading(false);
    }
  }

  void switchRole(String role) {
    _currentRole = role;
    _isAdmin = role != 'fisher';
    notifyListeners();
  }

  void _setLoading(bool value) {
    _isLoading = value;
    notifyListeners();
  }

  /// 设置用户信息
  void setUser(User user) {
    _user = user;
    notifyListeners();
  }

  /// 清除用户信息
  void clearUser() {
    _user = null;
    _roles = [];
    _permissions = [];
    _isAdmin = false;
    _currentRole = '';
    debugPrint('用户信息已清除');
    notifyListeners();
  }

  /// 保存用户信息到本地存储
  Future<void> _saveUserInfoToStorage(Map<String, dynamic> userData) async {
    try {
      await StorageUtil.saveUserInfo(userData);
    } catch (e) {
    }
  }
}
